//
//  JQHomeItemVC.m
//  JQLive
//
//  Created by Bruce on 20/8/12.
//  Copyright © 2020年 JQLive. All rights reserved.
//

#import "JQHomeItemVC.h"
#import "JQHomeCollectionViewCell.h"
//#import "JQAppDelegate.h"
#import "JQHomeCollectionReusableView.h"
#import "JQHomeBannerCollectionReusableView.h"

#import "JQHomeBannerModel.h"
#import "JQHomeLiveListModel.h"


//#define SCREEN_WIDTH ([[UIScreen mainScreen] bounds].size.width)

@interface JQHomeItemVC ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout, DZNEmptyDataSetSource>

@property(strong,nonatomic) UICollectionView *collectionView;
@property(nonatomic, assign) NSInteger pageNum;
@property (nonatomic, copy) NSArray<JQHomeBannerData *> *bannerDataArr;
@property (nonatomic, copy) NSArray<JQHomeLiveListRows *> *liveListRowArr;

@end

@implementation JQHomeItemVC

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    [self.view addSubview:self.collectionView];
    self.view.backgroundColor = [UIColor clearColor];
    self.collectionView.backgroundColor = [UIColor clearColor];
    //    self.collectionView.backgroundColor = kColorWithHex(0xF2F4FC);
//    self.collectionView.frame = self.view.bounds;
//    self.collectionView.frame = CGRectMake(0, MY_NavHeight, SCREEN_WIDTH, SCREEN_HEIGHT- MY_NavHeight -MY_BottomTabbarHeight);
    
//    [self.collectionView.mj_header beginRefreshing];
    [self loadData];
}
#pragma mark - Getters and Setters
- (UICollectionView *)collectionView {
    if (_collectionView == nil) {
        
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        layout.scrollDirection = UICollectionViewScrollDirectionVertical;
        
//        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
        _collectionView = [[UICollectionView alloc] initWithFrame:[UIScreen mainScreen].bounds collectionViewLayout:layout];
        _collectionView.backgroundColor = [UIColor clearColor];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.emptyDataSetSource = self;
        MY_WEAK;
        _collectionView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
            MY_STRONG;
            self.pageNum++;
            [strongSelf loadData];
        }];
        _collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            MY_STRONG;
            strongSelf.pageNum = 1;
            [strongSelf loadData];
        }];
//        [self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"testCollectionCell"];
//        [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"testHeader"];
        
        [self.collectionView registerClass:[JQHomeCollectionViewCell class] forCellWithReuseIdentifier:NSStringFromClass([JQHomeCollectionViewCell class])];
        [self.collectionView registerClass:[JQHomeCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:NSStringFromClass([JQHomeCollectionReusableView class])];
        [self.collectionView registerClass:[JQHomeBannerCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:NSStringFromClass([JQHomeBannerCollectionReusableView class])];
    }
    return _collectionView;
}
// 数据加载
- (void)loadData{
    
    NSLog(@"数据加载 请求");
//    [self barrierLoad]// 栅栏
//    [self groupNotify]; // groupNotify
//    [self groupWait]; // groupWait
//    [self groupEnterAndLeave];// groupEnterAndLeave
    
//    [self groupNotifyCRN];
    
    [self bannerLoad];
    [self appListLoad];
//    [self.collectionView reloadData];
    
    [self endFreash];
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
//    [self.collectionView reloadData];
}
/**
 * 队列组 dispatch_group_notify
 */
- (void)groupNotifyCRN {
    NSLog(@"currentThread---%@",[NSThread currentThread]);  // 打印当前线程
    NSLog(@"group---begin");
    
    dispatch_group_t group =  dispatch_group_create();
    dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [self bannerLoad];
        // 追加任务 1
        NSLog(@"currentThread 1---%@",[NSThread currentThread]);      // 打印当前线程
    });
    
    dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        // 追加任务 2
        [self appListLoad];
        NSLog(@"currentThread 2---%@",[NSThread currentThread]);      // 打印当前线程
    });
    
    dispatch_group_notify(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        dispatch_group_async(group, dispatch_get_main_queue(), ^{
            // 等前面的异步任务 1、任务 2 都执行完毕后，回到主线程执行下边任务
            NSLog(@"currentThread 3---%@",[NSThread currentThread]);      // 打印当前线程
            [self.collectionView reloadData];
            
            NSLog(@"group---end");
        });
    });
}
/**
 * 队列组 dispatch_group_enter、dispatch_group_leave
 */
- (void)groupEnterAndLeave {
    NSLog(@"currentThread---%@",[NSThread currentThread]);  // 打印当前线程
    NSLog(@"group---begin");
    
    dispatch_group_t group = dispatch_group_create();
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_group_enter(group);
    dispatch_async(queue, ^{
        // 追加任务 1
        
        [self bannerLoad];
        NSLog(@"currentThread 1---%@",[NSThread currentThread]);      // 打印当前线程

        dispatch_group_leave(group);
    });
    
    dispatch_group_enter(group);
    dispatch_async(queue, ^{
        // 追加任务 2
        [self appListLoad];
        NSLog(@"currentThread 2---%@",[NSThread currentThread]);      // 打印当前线程
        
        dispatch_group_leave(group);
    });
    
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        // 等前面的异步操作都执行完毕后，回到主线程.
        [self.collectionView reloadData];
        NSLog(@"currentThread 3---%@",[NSThread currentThread]);      // 打印当前线程
    
        NSLog(@"group---end");
    });
}
/**
 * 队列组 dispatch_group_wait
 */
- (void)groupWait {
    NSLog(@"currentThread---%@",[NSThread currentThread]);  // 打印当前线程
    NSLog(@"group---begin");
    
    dispatch_group_t group =  dispatch_group_create();
    
    dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        // 追加任务 1
        [self bannerLoad];
        NSLog(@"currentThread 1---%@",[NSThread currentThread]);      // 打印当前线程
    });
    
    dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        // 追加任务 2
        [self appListLoad];
        NSLog(@"currentThread 2---%@",[NSThread currentThread]);      // 打印当前线程
    });
    
    // 等待上面的任务全部完成后，会往下继续执行（会阻塞当前线程）
    dispatch_group_wait(group, DISPATCH_TIME_FOREVER);
    
    [self.collectionView reloadData];
    
    NSLog(@"group---end");
    
}
/**
 * 队列组 dispatch_group_notify
 */
- (void)groupNotify {
    NSLog(@"currentThread---%@",[NSThread currentThread]);  // 打印当前线程
    NSLog(@"group---begin");
    
//    dispatch_queue_t dispatchQueue = dispatch_queue_create("hyq.queue.next", DISPATCH_QUEUE_CONCURRENT);
//    dispatch_group_t dispatchGroup = dispatch_group_create();
//    dispatch_group_async(dispatchGroup, dispatchQueue, ^(){
//        NSLog(@"任务A");
//    });
//    dispatch_group_async(dispatchGroup, dispatchQueue, ^(){
//        NSLog(@"任务B");
//    });
//    dispatch_group_async(dispatchGroup, dispatchQueue, ^(){
//        NSLog(@"任务C");
//    });
//    dispatch_group_async(dispatchGroup, dispatchQueue, ^(){
//        NSLog(@"任务D");
//    });
//    dispatch_group_notify(dispatchGroup, dispatch_get_main_queue(), ^(){
//        NSLog(@"end");
//    });

    
//    dispatch_group_t group =  dispatch_group_create();
//    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_queue_t queue = dispatch_queue_create("hyq.queue.next", DISPATCH_QUEUE_CONCURRENT);
    dispatch_group_t group = dispatch_group_create();
    dispatch_group_async(group, queue, ^{
        // 追加任务 1
        NSLog(@"currentThread 1---%@",[NSThread currentThread]);      // 打印当前线程
        [self bannerLoad];
    });
    
    dispatch_group_async(group, queue, ^{
        // 追加任务 2
        [self appListLoad];
        NSLog(@"currentThread 2---%@",[NSThread currentThread]);      // 打印当前线程
    });
    
//    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
    dispatch_group_notify(group, queue, ^{
        // 等前面的异步任务 1、任务 2 都执行完毕后，回到主线程执行下边任务
        dispatch_group_async(group, dispatch_get_main_queue(), ^{

            [self.collectionView reloadData];
            NSLog(@"currentThread 4---%@",[NSThread currentThread]);      // 打印当前线程
        });
        NSLog(@"currentThread 3---%@",[NSThread currentThread]);      // 打印当前线程

        NSLog(@"group---end");
    });
}
// 栅栏 请求
- (void)barrierLoad{
    dispatch_queue_t queue = dispatch_queue_create("JQ_home", DISPATCH_QUEUE_CONCURRENT);
    dispatch_async(queue, ^{
        if (self.pageNum == 1) {
            NSLog(@"currentThread 1:%@", [NSThread currentThread]);
            [self bannerLoad];
        }
    });
    dispatch_async(queue, ^{
        NSLog(@"currentThread 2:%@", [NSThread currentThread]);
        [self appListLoad];
    });
    
    dispatch_barrier_sync(queue, ^{
        NSLog(@"currentThread 3:%@", [NSThread currentThread]);
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"currentThread barrier:%@", [NSThread currentThread]);
            [self.collectionView reloadData];
        });
    });
}
- (void)bannerLoad{
    //    category banner分类, 1:首页banner 2:娱乐banner  terminal 终端类型, 0:默认 1:ios 2:安卓 3:海外ios 4:web, get
    NSDictionary *bannerParam = @{@"category":@"1", @"terminal":@"1"};
    MY_WEAK;
//    [MYTipUtils showLoadingAlertString:nil inView:self.view];
    [MYTipUtils showLoading];
    [MYRequesTool MY_live_banner_RequestWithParam:bannerParam successHandle:^(id  _Nonnull response) {
        MY_STRONG;
        [MYTipUtils hideAllTips];
        NSLog(@"response1：%@", response);
        NSLog(@"currentThread 1-1:%@", [NSThread currentThread]);
        JQHomeBannerModel *model = [JQHomeBannerModel mj_objectWithKeyValues:response];
        if (model.code == 200) {
            if (model.data.count == 0) {
                // 无banner
                strongSelf.emptyString = @"暂无数据";
                return;
            }
            strongSelf.bannerDataArr = [model.data copy];
            
            // 是否主线程 返回主线程
    
//            if (strongSelf.collectionView.numberOfSections) {
//                NSIndexSet *indexSet = [NSIndexSet indexSetWithIndex:0];
//                [strongSelf.collectionView reloadSections:indexSet];
//            }else{
//                [strongSelf.collectionView reloadData];
//            }

//            [strongSelf.collectionView reloadData];
            dispatch_main_async_safe(^{
                [strongSelf.collectionView reloadData];
            });
            
#pragma mark - 测试5
//            NSIndexSet *indexSet = [NSIndexSet indexSetWithIndex:0];
//            [strongSelf.collectionView reloadSections:indexSet];
        }

    } failureHandle:^(NSError * _Nonnull error) {
        NSLog(@"error:%@", error);
        MY_STRONG;
        [strongSelf endFreash];
        [MYTipUtils hideAllTips];
    }];
}
// 直播列表请求
- (void)appListLoad{
    //    page size roomTagId 房间标签ID get page=1&size=20
    NSDictionary *param = @{@"page":@(self.pageNum), @"size":@"20"};
    MY_WEAK;
//    [MYTipUtils showLoadingAlertString:nil inView:self.view];
    [MYRequesTool MY_live_rooms_appList_RequestWithParam:param successHandle:^(id  _Nonnull response) {
        MY_STRONG;
        [MYTipUtils hideAllTips];
        [strongSelf endFreash];
        NSLog(@"currentThread 2-1:%@", [NSThread currentThread]);
        NSLog(@"response2：%@", response);
        JQHomeLiveListModel *model = [JQHomeLiveListModel mj_objectWithKeyValues:response];
        if (model.code == 200) {
            if (model.data.rows.count == 0) {
                if (strongSelf.pageNum == 1) {
                    // 暂无数据
                    strongSelf.emptyString = @"暂无数据";
                }else{
                    // 无更多数据
                    [strongSelf.collectionView.mj_footer endRefreshingWithNoMoreData];
                }
                return;
            }
            if (strongSelf.pageNum == 1) {
                strongSelf.liveListRowArr = [model.data.rows copy];
            }else{
                NSMutableArray *arrM = [NSMutableArray arrayWithArray:strongSelf.liveListRowArr];
                [arrM addObjectsFromArray:model.data.rows];
                strongSelf.liveListRowArr = [arrM copy];
            }
            
//            if (strongSelf.collectionView.numberOfSections) {
//                if (strongSelf.pageNum > 1){
//                    NSIndexSet *indexSet1 = [NSIndexSet indexSetWithIndex:1];
//                    [strongSelf.collectionView reloadSections:indexSet1];
//                    return;
//                }
//                NSIndexSet *indexSet = [NSIndexSet indexSetWithIndex:0];
//                [strongSelf.collectionView reloadSections:indexSet];
//                if (strongSelf.collectionView.numberOfSections>=2) {
//                    NSIndexSet *indexSet1 = [NSIndexSet indexSetWithIndex:1];
//                    [strongSelf.collectionView reloadSections:indexSet1];
//                }
//            }else{
//                [strongSelf.collectionView reloadData];
//            }
            dispatch_main_async_safe(^{
                [strongSelf.collectionView reloadData];
            });
              
#pragma mark - 测试6
//            [strongSelf.collectionView reloadSections:[NSIndexSet indexSetWithIndex:0]];
        }

    } failureHandle:^(NSError * _Nonnull error) {
        NSLog(@"error:%@", error);
        [MYTipUtils hideAllTips];
        MY_STRONG;
        [strongSelf endFreash];
    }];
}
#pragma mark - Private Methods
- (void)endFreash{
    if (self.collectionView.mj_header.isRefreshing) {
        [self.collectionView.mj_header endRefreshing];
    }
    if (self.collectionView.mj_footer.isRefreshing) {
        [self.collectionView.mj_footer endRefreshing];
    }
}
#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    NSLog(@"-----------    %lf",scrollView.contentOffset.y);

#pragma mark - 测试0
//    return;
    
    // 设置下拉距离
    if (scrollView.contentOffset.y <= -MY_TopSafeMargin-60) {
        //        scrollView.contentOffset.y = 17;
        [scrollView setContentOffset:CGPointMake(0,-MY_TopSafeMargin-60) animated:NO];
    }
    
    if (scrollView.contentOffset.y < -MY_TopSafeMargin+44) {
        self.collectionView.backgroundColor = [UIColor clearColor];
    }else{
        //        self.collectionView.backgroundColor = [UIColor whiteColor];
        self.collectionView.backgroundColor = kColorWithHex(0xF2F4FC);
    }
}
#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    //  return self.arr.count;
    
    if (section == 0) {
        if (self.liveListRowArr.count <=4) {
            return self.liveListRowArr.count;
        }else{
            return 4;
        }
    }else{
        return self.liveListRowArr.count-4;
    }
}

// The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
   
#pragma mark - 测试1
//    UICollectionView *testCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"testCollectionCell" forIndexPath:indexPath];
//    testCell.backgroundColor = [UIColor redColor];
//    return testCell;
    
    JQHomeCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([JQHomeCollectionViewCell class]) forIndexPath:indexPath];
#pragma mark - 测试2 报错必须使用 dequeueReusableCellWithReuseIdentifier: forIndexPath:初始化
//    JQHomeCollectionViewCell *cell = [[JQHomeCollectionViewCell alloc] init];
    
    [cell.imageView sd_cancelCurrentImageLoad];//加上此行代码
    
    if (indexPath.section == 0) {
        [cell setRowModelWith:self.liveListRowArr[indexPath.row]];
    }else{
        [cell setRowModelWith:self.liveListRowArr[indexPath.row+4]];
    }
    return cell;
}


- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    
    //    if (self.liveListRowArr.count == 0){
    //        return 2;
    //    }
//    return 1;
    
    if (self.liveListRowArr.count == 0){
        return 0;
    }
    if (self.liveListRowArr.count <= 4) {
        return 1;
    }
    return 2;
}


- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    
    UICollectionReusableView *reusable = [UICollectionReusableView new];
    if (kind == UICollectionElementKindSectionHeader) {
        
#pragma mark - 测试3 必须使用dequeueReusableSupplementaryViewOfKind:withReuseIdentifier:forIndexPath:初始化
//        return reusable;
        
        if (indexPath.section == 0){
            JQHomeBannerCollectionReusableView *view = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:NSStringFromClass([JQHomeBannerCollectionReusableView class]) forIndexPath:indexPath];
            
            view.title.text = @"精彩推荐";//[[NSString alloc] initWithFormat:@"头部视图%ld",indexPath.section];
            view.title.textColor = [UIColor blackColor];
            view.title.font = [UIFont systemFontOfSize:16];
            view.dataArr = [self.bannerDataArr copy];
            [view updataWithBanner];
            reusable = view;
        }else{
            
            JQHomeCollectionReusableView *view = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:NSStringFromClass([JQHomeCollectionReusableView class]) forIndexPath:indexPath];
            view.title.text = @"全部直播";//[[NSString alloc] initWithFormat:@"头部视图%ld",indexPath.section];
            view.title.textColor = [UIColor blackColor];
            view.title.font = [UIFont systemFontOfSize:16];
            reusable = view;
            
        }
    }
    return reusable;
}

#pragma mark - UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    NSString *message = [[NSString alloc] initWithFormat:@"你点击了第%ld个section，第%ld个cell",(long)indexPath.section,(long)indexPath.row];
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //点击确定后执行的操作；
    }]];
    [self presentViewController:alert animated:true completion:^{
        //显示提示框后执行的事件；
    }];
}

#pragma mark - UICollectionViewDelegateFlowLayout
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    // return CGSizeMake((SCREEN_WIDTH - 24) / 2, (SCREEN_WIDTH - 24) / 2);
    return CGSizeMake((SCREEN_WIDTH - 26) / 2, (SCREEN_WIDTH - 26)*98/174 / 2 + 52);
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    //    if ()
    return UIEdgeInsetsMake(10, 10, 0, 10);
    //    return UIEdgeInsetsMake(0, 0, 0, 0);
    //    return UIEdgeInsetsMake(20, 20, 10, 20);
}
// 横向
- (CGFloat)collectionView:(UICollectionView*)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 6;
}
// 纵向
- (CGFloat)collectionView:(UICollectionView*)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 6;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
#pragma mark - 测试4 CGSizeMake(0, 0)表示 collect head没有不走 collect head 初始化赋值
//    return CGSizeMake(0, 0);
    if (section == 0) {
        return CGSizeMake(SCREEN_WIDTH,144 +42+20);
    }
    return CGSizeMake(SCREEN_WIDTH, 44);
}

@end

